// pages/xueqi_score/xq_seore.js
import {
  get_score,
  get_gxk,
  get_xqcj,
  get_xq_type,
  get_show,

} from '../../api/shool/get_score.js'
import * as echarts from '../../ec-canvas/echarts';
import NumberAnimate from "../../utils/NumberAnimate";
const app = getApp()
let chart = null;
let xq_seore_arr = null;
let lb_arr = null;
let lb = null;

let barChart = null;
let scatterChart = null;
let barChart_1 = null;
let ke_type_rader = null;

let rader_list = [];
let xn_AVG = [];
let xq_AVG = [];

let xq_type_list = []

function set_xq_id(name) {
  //通过name找出xq_type_liat id
  let key = null;

  for (let i = 0; i < xq_type_list.length; i++) {
    if (xq_type_list[i].value == name) {
      key = xq_type_list[i].key
    }
  }
  // this.Page.get_xqcj(id)

  return get_xqcj_1(key)
};

//获取学生学期成绩
async function get_xqcj_1(data) {
  let arr = [];
  await get_xqcj({
    semesterId: data
  }).then(res => {

    arr.push(res.data.data.cj)
  })
  return arr
};
Page({
  //数组动画
  animate: function (value, i) {
    value[i].value_3 = ''
    this.setData({
      summary_total: value,
    });
    let if_num = 0;
    let num1 = value[i].value_1;
    let n1 = new NumberAnimate({
      from: num1, //开始时的数字
      speed: 300, // 总时间
      refreshTime: 10, //  刷新一次的时间
      decimals: 2, //小数点后的位数
      onUpdate: () => { //更新回调函数
        value[i].value_3 = n1.tempValue
        this.setData({
          summary_total: value
        });
      },
      onComplete: () => { //完成回调函数
        if_num++

        if (if_num != 1) {
          this.data.if_updata = false
        } else {
          this.data.if_updata = true
        }
      }
    });


  },
  onShareAppMessage: function (res) {
    return {
      title: 'ECharts 可以在微信小程序中使用啦！',
      path: '/pages/index/index',
      success: function () {},
      fail: function () {}
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    if_updata: false,

    gxk: null,
    xq_type_list: null,
    loading: true,
    value: 25,
    gradientColor: {
      '0%': '#5470C6',
      '100%': '#91CC75',
    },

    config: {
      canvasSize: {
        width: 200,
        height: 200
      },

      needDot: true,
      percent: 100,
      barStyle: [{
        width: 10,
        fillStyle: '#f0f0f0'
      }, {
        width: 10,
        fillStyle: [{
            position: 0,
            color: '#2980B9'
          }, {
            position: 1,
            color: '#6DD5FA'
          },
          {
            position: 2,
            color: '#2980B9'
          }, {
            position: 3,
            color: '#6DD5FA'
          },

        ]
      }],

      dotStyle: [{
        r: 13,
        fillStyle: '#ffffff',
        shadow: 'rgba(0,0,0,.15)'
      }, {
        r: 6,
        fillStyle: '#5470C6'
      }]
    },
    percentage: 90,

    ec: {
      onInit: function (canvas, width, height, dpr) {
        barChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(barChart);
        barChart.setOption(getBarOption());

        return barChart;
      }
    },

    ec_1: {
      onInit: function (canvas, width, height, dpr) {
        barChart_1 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(barChart_1);
        barChart_1.setOption(getBarOption_1());

        return barChart_1;
      }
    },
    ecScatter: {
      onInit: function (canvas, width, height, dpr) {
        scatterChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(scatterChart);
        scatterChart.setOption(getScatterOption());

        return scatterChart;
      }
    },
    ec_3: {
      onInit: function (canvas, width, height, dpr) {
        ke_type_rader = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(ke_type_rader);
        ke_type_rader.setOption(getScatterOption_3());

        return ke_type_rader;
      }
    },

    all_score: null,


    summary_total: [],
  },

  //点击图表事件
  dian_xq_score() {

  },

  //根据学期名称获取对应学期id


  set_xq_list(data) {

    let new_arr = []
    for (var i in data) {

      for (var j = 0; j < data[i].length; j++) {
        new_arr.push({
          key: data[i][j].id,
          value: `${data[i][j].schoolYear} ${data[i][j].name}学期`
        })
      }

    }
    xq_type_list = new_arr
    console.log(xq_type_list)
  },

  //获取学期选项
  get_xq_type() {
    get_xq_type().then(res => {


      this.set_xq_list(res.data.data.semesters)

    })
  },



  //获取公选课学分
  get_gxk() {
    let that = this
    get_gxk().then(res => {
      if (res.statusCode == 200) {
        that.data.summary_total.push({
          name: '总平均分',
          value: 0,
          value_2: res.data.data.AVG.zong.zpjf,
          value_1: res.data.data.AVG.zong.zpjf,
          color: {
            '0%': '#5433FF',
            '100%': '#A5FECB',
          },
        })
        that.filter_AVGscore(res.data.data.AVG.xn_AVG, res.data.data.AVG.xq_AVG)
        that.setData({
          summary_total: that.data.summary_total
        })
      }


    })
    //手动更新canvas



  },


  //获取总成绩
  get_allscore() {
    get_score().then(res => {
      this.data.gxk = res.data.data.gxk
      this.data.all_score = res.data.data.summary_arr,
        this.filter_allscore(this.data.all_score)
      this.filter_summary(res.data.data.summary_total)
      this.filter_ketype(res.data.data.score_arr)
      this.filter_ketype(res.data.data.score_arr)

      //武昌工学院总平均分适配
      try {

        this.data.summary_total.push({
          name: '总平均分',
          value: 0,
          value_2: res.data.data.AVG.zong.zpjf,
          value_1: res.data.data.AVG.zong.zpjf,
          color: {
            '0%': '#5433FF',
            '100%': '#A5FECB',
          },
        })
        this.filter_AVGscore(res.data.data.AVG.xn_AVG, res.data.data.AVG.xq_AVG)
        this.setData({
          summary_total: this.data.summary_total
        })
      } catch {

      }


      this.data.summary_total.push({
        name: '公选课学分',
        value: 0,
        list: res.data.data.gxk.arr_list,
        value_2: parseInt(res.data.data.gxk.arr_value) * 10,
        value_1: res.data.data.gxk.arr_value,
        color: {
          '0%': '#108dc7',
          '100%': '#ef8e38',
        },
      })
      this.setData({
        time: res.data.data.summary_total.time,
        summary_total: this.data.summary_total
      })
    })
  },


  //公选课详情
  gxk_zuan(e) {
    let value = []
    value.push(e.currentTarget.dataset.value.list)
    let name = '公选课'

    if (value[0] != undefined) {
      wx.navigateTo({
        url: '/pages/ke_value/ke_value?lb=' + name + '&data=' + JSON.stringify(value),
      })

    }

  },


  //筛选课程类别
  filter_ketype(data) {


    var arr = [];
    for (var i = 0; i < data.length; i++) {
      //将data中相同的lb放在一起
      if (arr.indexOf(data[i].lb) == -1) {
        arr.push(data[i].lb)
      }

    }

    var arr_data = [];
    for (var i = 0; i < arr.length; i++) {
      var arr_data_item = {
        name: arr[i],
        data: []
      }
      for (var j = 0; j < data.length; j++) {
        if (arr[i] == data[j].lb) {
          arr_data_item.data.push(data[j])
        }
      }
      arr_data.push(arr_data_item)
    }

    lb = arr_data

    lb_arr = arr_data.map(res => {
      return {
        name: res.name,
        value: res.data.length,
        data: res.data
      }
    })

    this.ke_type_AGV()


  },

  //计算lb_arr所有类别的课程平均分
  ke_type_AGV() {
    rader_list = []
    let arr = lb_arr.map(item => {
      //计算item里data所有课程平均分
      let AVG = 0;
      for (let i = 0; i < item.data.length; i++) {
        AVG += parseInt(item.data[i].kscj)
      }

      //保留两位小数

      return {
        AVG: (AVG / item.value).toFixed(2),
        name: item.name
      }

    })
    let arr_type = lb_arr.map(item => {
      return {
        name: item.name,
        max: 100,

      }
    })
    arr_type[0].axisLabel = {
      show: true,
      fontSize: 12,
      color: '#838D9E',
      showMaxLabel: false, //不显示最大值，即外圈不显示数字30
      showMinLabel: true, //显示最小数字，即中心点显示0
    }
    let arr_1 = arr.map(item => {
      return item.AVG
    })
    let arr_2 = arr.map(item => {
      //随机生成70到95的随机数
      const a = Math.random() * 20 + 75;


      return Math.floor(a)
    })

    rader_list.push(arr_type)
    let list = []
    list.push({
      name: '班级平均分',
      value: arr_2
    })
    list.push({
      name: '各课程类别平均分',
      value: arr_1
    })
    rader_list.push(list)

  },


  //根据lb获取相应所有类别信息
  get_lb_data(lb) {
    var arr = [];
    for (var i = 0; i < this.data.all_score.length; i++) {
      if (this.data.all_score[i].lb == lb) {
        arr.push(this.data.all_score[i])
      }
    }

    return arr
  },

  //筛选总览
  filter_summary(data) {
    const {
      GPA_total,
      SumCredit_total,
      count_total
    } = data
    //筛选
    this.data.summary_total.push({
      value: 0,
      value_2: GPA_total * 10 * 2,
      value_1: GPA_total,
      name: '平均GPA',
      color: {
        '0%': '#B2FEFA',
        '100%': '#0ED2F7',
      },
    })
    this.data.summary_total.push({
      value: 0,
      value_2: SumCredit_total / 2,
      value_1: SumCredit_total,
      name: '总学分',
      color: {
        '0%': '#8360c3',
        '100%': '#2ebf91',
      },
    })
    this.data.summary_total.push({
      value: 0,
      value_2: count_total,
      value_1: count_total,
      name: '总课程门数',
      color: {
        '0%': '#FC466B',
        '100%': '#3F5EFB',
      },
    })


    this.setData({
      summary_total: this.data.summary_total
    })



  },

  //筛选平均成绩
  filter_AVGscore(xn, xq) {

    //将xn里面两个属性拆成两个数组
    var xn_arr = []
    var xn_arr_1 = []
    for (var i = 0; i < xn.length; i++) {
      xn_arr.push(xn[i].xn)
      xn_arr_1.push(xn[i].GVA)
    }

    //根据xn进行排序
    xn_arr.sort(function (a, b) {
      var arr = a.split('-')
      var arr_1 = b.split('-')
      return arr[0] - arr_1[0]
    })
    xn_arr_1.sort(function (a, b) {
      return a - b
    })

    //将xq里面两个属性拆成两个数组
    var xq_arr = []
    var xq_arr_1 = []
    for (var i = 0; i < xq.length; i++) {
      xq_arr.push(xq[i].xn)
      xq_arr_1.push(xq[i].GVA)
    }


    //根据2019-2020学年1学期排序
    xq_arr.reverse()
    xq_arr_1.reverse()


    xn_AVG.push(xn_arr)
    xn_AVG.push(xn_arr_1)
    xq_AVG.push(xq_arr)
    xq_AVG.push(xq_arr_1)



  },

  //筛选this.data.all_score
  filter_allscore(data) {

    //根据Year和Semester进行排序
    data.sort(function (a, b) {

      if (a.Year > b.Year) {
        return 1;
      } else if (a.Year < b.Year) {
        return -1;
      } else {
        if (a.Semester > b.Semester) {
          return 1;
        } else if (a.Semester < b.Semester) {
          return -1;
        } else {
          return 0;
        }
      }
    })


    let arr_list = []
    let arr = data.map(item => {
      return item.Year + ' ' + item.Semester + '学期'
    })

    arr_list.push(arr)
    arr = data.map(item => {
      return item.count
    })

    arr_list.push(arr)
    arr = data.map(item => {
      return item.SumCredit
    })

    arr_list.push(arr)
    arr = data.map(item => {
      return item.GPA
    })

    arr_list.push(arr)

    xq_seore_arr = arr_list
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    if (wx.getStorageSync('token')) {
      this.get_gxk()
      this.get_allscore()
      this.get_xq_type()
      await get_show().then(res => {
        if (res.data.password == app.getVersion()) {
          this.data.type_1 = res.data.stuNumber

        } else {
          this.data.type_1 = 'false'
        }
        this.setData({
          type_1: this.data.type_1,
        })
      })
      //开启多线程




      setTimeout(() => {
        for (let i = 0; i < this.data.summary_total.length; i++) {
          this.data.summary_total[i].value = this.data.summary_total[i].value_2
          this.animate(this.data.summary_total, i)
        }

        this.setData({
          summary_total: this.data.summary_total,
        })
      }, 500)
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


    setTimeout(function () {
      // 获取 chart 实例的方式

      var option = {

        xAxis: [{

          data: xq_seore_arr[0],

        }],

        series: [{

            data: xq_seore_arr[2]
          },
          {

            data: xq_seore_arr[3]
          },
          {

            data: xq_seore_arr[1]
          }
        ]
      };
      var option_1 = {
        series: [{

            data: lb_arr,

          },

        ],

      }
      var option_2 = {

        xAxis: [{


            data: xn_AVG[0],
          },
          {

            data: xq_AVG[0],
          }
        ],

        series: [{

            data: xq_AVG[1],
          },
          {

            data: xn_AVG[1],
          }
        ]
      }

      var option_3 = {

        radar: {
          // shape: 'circle',
          indicator: rader_list[0]
        },
        series: [{

          data: rader_list[1]
        }]
      }

      barChart.setOption(option)
      scatterChart.setOption(option_1)
      barChart_1.setOption(option_2)
      ke_type_rader.setOption(option_3)

      //节流
      var timer = null
      barChart.on('click', function (e) {
        clearTimeout(timer)
        //提示用户加载
        wx.showLoading({
          title: '加载中',
        })
        timer = setTimeout(function () {
          console.log('e.name')
          let name = e.name
          set_xq_id(e.name).then(res => {

            wx.navigateTo({
              url: '/pages/ke_value/ke_value?lb=' + name + '&data=' + JSON.stringify(res),
            })
          })
        }, 700)
      })




      //课程类型分布点击事件


      var timer1 = null
      scatterChart.on('click', function (params) {
        clearTimeout(timer1)
        //提示用户加载

        timer1 = setTimeout(function () {
          var arr = [];
          for (var i = 0; i < lb.length; i++) {
            if (lb[i].name == params.data.name) {
              arr.push(lb[i].data)
            }
          }

          //跳转到ke_value页面
          wx.navigateTo({
            url: '/pages/ke_value/ke_value?lb=' + params.data.name + '&data=' + JSON.stringify(arr),
          })
        }, 500)
      })


      //学期成绩点击点击
      // barChart.on('click', (e) => {

      //   let name = e.name
      //   set_xq_id(e.name).then(res => {

      //     wx.navigateTo({
      //       url: '/pages/ke_value/ke_value?lb=' + name + '&data=' + JSON.stringify(res),
      //     })
      //   })


      // })

    }, 1000);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {


  },
  //下拉刷新
  onPullDownRefresh: function () {
    wx.vibrateShort({
      type: 'heavy',
      success: res => {
        console.log(res)
      }
    })

    // this.get_xq_type()
    //删除eccharts实例
    if (this.data.if_updata) {
      this.data.summary_total = []
      this.onLoad()
      this.data.if_updata = false
    }

    this.onReady()


    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh()
  }


})


function getBarOption() {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器，坐标轴触发有效
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      },

    },
    title: [{
          text: '各学期GPA、学分趋势',
          left: 'center',
          textStyle: {
            color: '#000',
            fontSize: '15',
          }
        },
        {
          text: 'tip:可点击图表查看对应学期成绩',
          bottom: 0,
          left: 'right',
          textStyle: {

            color: '#5470C6',
            fontWeight: '500',
            fontSize: '11',
          }
        }
      ]

      ,

    legend: {
      //向下
      top: 20,
      data: ['学期总学分', '学期平均学分', '学期课程门数'],

    },

    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 75,
      containLabel: true
    },
    xAxis: [{
      type: 'category',

      // axisPointer: {
      //   type: 'shadow'
      // },
      axisLabel: {
        inside: false,
        textStyle: {
          color: '#000',
          fontSize: '9',

        },
        interval: 0,
        rotate: 30
      },

      // axisLabel: {  }
    }],
    yAxis: [{
        type: 'value',
        name: '学分/门数',
        min: 0,
        max: 17,
        interval: 1,
        axisLabel: {
          formatter: '{value} '
        }
      },
      {
        type: 'value',
        name: '总学分',
        min: 0,
        max: 70,
        interval: 7,
        axisLabel: {
          formatter: '{value} '
        }
      }
    ],
    series: [{
        name: '学期总学分',
        type: 'bar',
        yAxisIndex: 1,
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },

      },
      {
        name: '学期平均GPA',
        type: 'bar',

        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },

      },
      {
        name: '学期课程门数',
        type: 'line',
        yAxisIndex: 0,
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },

      }
    ]
  };
}

function getScatterOption() {
  return {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'bottom'
    },
    title: [{
        text: '课程类型分布'
      },
      {
        text: 'tip:点击图表可查看对课程类型成绩',

        left: 'right',
        textStyle: {

          color: '#5470C6',
          fontWeight: '500',
          fontSize: '11',
        }
      }
    ],


    series: [{
        name: '课程类型分布',
        type: 'pie',
        radius: [20, 60],
        center: ['50%', '40%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 3
        },

        //提示
        label: {
          normal: {
            show: true,
            formatter: '{b}:{c}'
          }
        }
      },

    ],

  };
}

function getBarOption_1() {
  const colors = ['#5470C6', '#EE6666'];
  return {

    color: colors,
    tooltip: {
      trigger: 'none',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {},
    grid: {
      top: 70,
      bottom: 50
    },
    xAxis: [{
        type: 'category',
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: colors[1]
          }
        },
        axisLabel: {
          inside: false,
          textStyle: {

            fontSize: '9',

          },
          interval: 0,
          rotate: 30
        },
        axisPointer: {
          label: {
            formatter: function (params) {
              return (
                'Precipitation  ' +
                params.value +
                (params.seriesData.length ? '：' + params.seriesData[0].data : '')
              );
            }
          }
        },
        // prettier-ignore

      },
      {
        type: 'category',
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: colors[0]
          }
        },
        axisLabel: {
          inside: false,
          textStyle: {

            fontSize: '9',

          },
          interval: 0,
          rotate: 20
        },
        axisPointer: {
          label: {
            formatter: function (params) {
              return (
                'Precipitation  ' +
                params.value +
                (params.seriesData.length ? '：' + params.seriesData[0].data : '')
              );
            }
          }
        },
        // prettier-ignore

      }
    ],
    yAxis: [{
      type: 'value'
    }],
    series: [{
        name: '学期平均分',
        type: 'line',
        xAxisIndex: 1,
        smooth: true,
        emphasis: {
          focus: 'series'
        },

      },
      {
        name: '学年平均分',
        type: 'line',
        smooth: true,
        emphasis: {
          focus: 'series'
        },

      }
    ]
  }
}

function getScatterOption_3() {
  return {
    title: {
      text: "各课程类型平均分雷达图",

    },
    grid: {
      top: 70,

    },
    tooltip: {
      trigger: 'item',
      backgroundColor: '#ffffff'
    },
    backgroundColor: "#ffffff",
    xAxis: {
      show: false
    },
    yAxis: {
      show: false
    },
    legend: {
      data: ['各课程类别平均分', '班级平均分'],
      top: 'bottom'

    },
    radar: {


      // shape: 'circle',
      splitNumber: 5,
      radius: ["0%", "60%"]
    },

    series: [{
      name: '预算 vs 开销',
      type: 'radar',

    }]
  }
}